/**
 * Created by lvlq on 16/4/24.
 */
var express = require("express");
var router = express.Router();
var Q = require("q");
var wxshare = require("../mid/wxshare");
var oAuth = Util("wx.oAuth");
var Api = Util("wx.api");
var querystring = require("querystring");
var sequelize = require("sequelize");

const TRUE = 1;
const FALSE = 0;
const TYPE_MINE = 1;
const TYPE_SHARE = 2;

/**
 * oauth2.0回调函数 获取用户信息
 */
router.get("/oauth", function (req, res) {
    var code = req.query.code;
    if (code) {
        oAuth.getUserByCode(code, function (err, result) {
            if (!err) {
                req.session.user = result;
                addWxUser(result.openid, result.nickname).then(function () {
                    res.redirect(req.session.oauthurl);
                }).catch(function (err) {
                    console.error(err);
                    res.send("系统错误~请联系管理员~~");
                });
            } else {
                console.error(err);
                res.send("系统错误~请联系管理员~~");
            }
        });
    } else {
        res.send("未同意授权无法访问网页");
    }
});

/**
 * session 判断
 *
 * 进行oAuth页面跳转
 */
router.get("/*", function (req, res, next) {
    var type = req.query.type || TYPE_MINE;
    var q_openid = req.query.q_openid;
    if (req.hostname == "localhost") {
        req.session.user = {
            openid: 'owUQswAmAVkFdFRY_aCtRSiw1Z4g',
            nickname: '吕立奇111',
            sex: 1,
            language: 'zh_CN',
            city: 'Dalian',
            province: 'Liaoning',
            country: 'CN',
            headimgurl: 'http://wx.qlogo.cn/mmopen/Q3auHgzwzM59E1IFfoXEsgtXdrCA9E1jN7FBnAAQSIoZ2My3D5uX7sA45BHXgC1JrzqZhry3epS4GTSa40Hseg/0',
            privilege: [],
            type: 'userinfo'
        };
        addWxUser("owUQswAmAVkFdFRY_aCtRSiw1Z4g", "吕立奇111").then(function () {
            next();
        }).catch(function (err) {
            console.err(err);
            res.send("系统错误~请联系管理员~~");
        });
    } else {
        if (!req.session.user) {
            var str = querystring.stringify({
                type: type,
                q_openid: q_openid
            });
            req.session.oauthurl = "/index/pumpUp/index?" + str;
            var url = oAuth.getAuthorizeURL('http://mzrq.weixinzjit.com/index/pumpUp/oauth', '', 'snsapi_userinfo');
            res.redirect(url);
        } else {
            next();
        }
    }


});

/**
 * 分享信息设置
 */
router.get("/*", wxshare());
router.get("/*", function (req, res, next) {
    res.locals.title = "玛足人气，加油打气";

    var type = req.query.type || TYPE_MINE;
    var q_openid = req.query.q_openid;
    var openid;
    if (type == TYPE_MINE) {
        openid = req.session.user.openid;
    } else {
        openid = q_openid;
    }

    getUserByOpenid(openid).then(function (data) {
        if (!data) return res.send("系统错误~请联系管理员~~");

        res.locals.share = {};
        res.locals.share.link = "http://mzrq.weixinzjit.com/index/pumpUp/index?type=" + TYPE_SHARE + "&q_openid=" + openid;
        res.locals.share.title = "玛足人气，加油打气";
        res.locals.share.img = "http://mzrq.weixinzjit.com/Public/index/image/share.jpg";
        res.locals.share.desc = "友谊的小船不能翻~ " + data.nick + "正在抢汤尤杯门票，急需你帮忙！";
        res.locals.share.qtitle = "快帮" + data.nick + "打气赢好礼，和玛吉斯一起为中羽加油！";
        //快帮XXXXX打气赢好礼，和玛吉斯一起为中羽加油！
        next();
    }).catch(function (err) {
        console.error(err);
        res.send("系统错误~请联系管理员~~");
    });
});

/**
 * 首页渲染
 */
router.get("/index", function (req, res) {
    var q_openid = req.query.q_openid;
    var openid = req.session.user.openid;

    if (q_openid == openid) {
        res.redirect("/index/pumpUp/index#/mine")
    } else {
        res.render("index.html");
    }

});


/**
 * 打气接口
 *  pid q_openid
 */
router.post("/clickAdd", function (req, res) {
    var pid = req.body.pid;
    var q_openid = req.body.q_openid;
    var openid = req.session.user.openid;
    if (q_openid == openid) {
        res.json({
            errno: 1010,
            errdesc: "不能给自己打气"
        });
        return;
    }
    checkUserClick(openid, q_openid).then(function (flag) {
        if (flag == FALSE) {
            throw new Error("您只能给好友打一次气哦~~");
        }
        return checkPrizeClick(pid, q_openid)
    }).then(function (flag) {
        if (flag == FALSE) {
            throw new Error("此奖品已经打满气了哦~~");
        }

        return insertLog(pid, openid, q_openid);
    }).then(function () {
        return getNumByPidAndOpenid(pid, q_openid);
    }).then(function (data) {
        res.json({
            errno: 0,
            data: data
        });
    }).catch(function (err) {
        res.json({
            errno: 10001,
            errdesc: err.message
        });
    });
});

/**
 * 获取打气数量
 * openid
 */
router.post("/getNum", function (req, res) {
    var result = {};
    var openid, type = req.body.type;

    if (type == TYPE_SHARE) {
        openid = req.body.openid;
    } else {
        openid = req.session.user.openid;
    }


    getNumByPidAndOpenid(1, openid).then(function (data) {
        result["1"] = data;
        return getNumByPidAndOpenid(2, openid);
    }).then(function (data) {
        result['2'] = data;
        return getNumByPidAndOpenid(3, openid);
    }).then(function (data) {
        result["3"] = data;
        return getUserByOpenid(openid);
    }).then(function (userinfo) {
        res.json({
            errno: 0,
            data: {
                result: result,
                userinfo: userinfo
            }
        });
    }).catch(function (err) {
        res.json({
            errno: 1002,
            errdesc: err.message
        });
    });
});

/**
 * 提交用户信息
 * name phone address
 */
router.post("/commitPhone", function (req, res) {
    var openid = req.session.user.openid;
    var phone = req.body.phone;
    saveUserPhone(openid, phone).then(function () {
        res.json({
            errno: 0
        });
    }).catch(function (err) {
        res.json({
            errno: 1020,
            errdesc: err.message
        });
    })
});

/**
 * 获取分享内容
 */
router.post("/getShareContent", function (req, res) {
    var type = req.body.type || TYPE_MINE;
    var openid;

    if (type == TYPE_MINE) {
        openid = req.session.user.openid;
    } else {
        openid = req.body.q_openid;
    }

    getUserByOpenid(openid).then(function (data) {
        var share = {};
        share.link = "http://mzrq.weixinzjit.com/index/pumpUp/index?type=" + TYPE_SHARE + "&q_openid=" + openid;
        share.title = "玛足人气，加油打气";
        share.img = "http://mzrq.weixinzjit.com/Public/index/image/share.jpg";
        share.desc = "友谊的小船不能翻~ " + data.nick + "正在抢汤尤杯门票，急需你帮忙！";
        share.qtitle = "快帮" + data.nick + "打气赢好礼，和玛吉斯一起为中羽加油！";
        res.json({
            errno: 0,
            data: share
        });
    }).catch(function () {
        res.json({
            errno: 1001
        });
    });
});

router.post("/checkUserPhone", function (req, res) {
    var Wx = M("index.wx");

    Wx.find({
        where: {
            openid: req.session.user.openid
        }
    }).then(function (user) {
        if (user && user.phone) {
            res.json({
                errno: 0
            })
        } else {
            throw new Error("1");
        }
    }).catch(function (err) {
        res.json({
            errno: 1001
        })
    })
});

router.post("/checkGuanZhu", function (req, res) {
    var openid = req.session.user.openid;

    Api.getUser(openid, function (err, data) {
        console.log(err, data);
        if (err) {
            res.json({
                errno: 1001
            });
        } else {
            if (!data) {
                res.json({
                    errno: 1001
                });
            } else {
                if (data.subscribe == 0) {
                    res.json({
                        errno: 1001
                    });
                } else {
                    res.json({
                        errno: 0
                    });
                }

            }
        }
    });
});


/**
 * 一个用户只能给另一个用户打一次气
 * 此方法就是用于判断上述条件的
 * @param openid
 * @param q_openid
 * @returns {jQuery.promise|promise.promise|*|promise|d.promise}
 */
var checkUserClick = function (openid, q_openid) {
    var defer = Q.defer();
    var Log = M("index.log");

    Log.find({
        where: {
            openid: openid,
            q_openid: q_openid
        }
    }).then(function (data) {
        if (data) {
            defer.resolve(FALSE);
        } else {
            defer.resolve(TRUE);
        }

    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

/**
 * 判断用户是否可以被点
 * @param pid
 * @param q_openid
 * @returns {*|jQuery.promise|promise.promise|promise|d.promise}
 */
var checkPrizeClick = function (pid, q_openid) {
    var defer = Q.defer();
    var Pirze = M("index.prize");
    var Log = M("index.log");
    var num, already_num;
    Pirze.find({
        where: {
            id: pid
        }
    }).then(function (data) {
        num = data.num;

        return Log.count({
            where: {
                pid: pid,
                q_openid: q_openid
            }
        });

    }).then(function (count) {
        already_num = count;

        if (already_num >= num) {
            defer.resolve(FALSE);
        } else {
            defer.resolve(TRUE);
        }
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

/**
 * 插入log数据
 * @param pid
 * @param openid
 * @param q_openid
 * @returns {promise.promise|jQuery.promise|*|promise|d.promise}
 */
var insertLog = function (pid, openid, q_openid) {
    var defer = Q.defer();
    var Log = M("index.log");

    Log.create({
        pid: pid,
        openid: openid,
        q_openid: q_openid
    }).then(function () {
        defer.resolve();
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

/**
 * 获取用户指定奖品的点击次数
 * @param pid
 * @param openid
 * @returns {jQuery.promise|promise.promise|*|promise|d.promise}
 */
var getNumByPidAndOpenid = function (pid, openid) {
    var defer = Q.defer();
    var Log = M("index.log");
    var Prize = M("index.prize");
    var num, already_num;

    Prize.find({
        where: {
            id: pid
        }
    }).then(function (data) {
        num = data.num;

        return Log.count({
            where: {
                pid: pid,
                q_openid: openid
            }
        });
    }).then(function (count) {
        already_num = count;

        if (already_num > num) already_num = num;

        defer.resolve({
            num: num,
            already_num: already_num
        });
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};

/**
 * 获取用户信息
 * @param openid
 * @returns {jQuery.promise|promise.promise|*|promise|d.promise}
 */
var getUserByOpenid = function (openid) {
    var defer = Q.defer();
    var Wx = M("index.wx");
    Wx.find({
        where: {
            openid: openid
        }
    }).then(function (userinfo) {
        if (userinfo)
            userinfo.nick = new Buffer(userinfo.nick, 'base64').toString();
        defer.resolve(userinfo);
    }).catch(function (err) {
        defer.reject(err);
    });


    return defer.promise;
};

/**
 * 判断用户是否存在,不存在则插入用户
 * @param openid
 * @param nick
 * @returns {*|promise.promise|jQuery.promise|d.promise|promise}
 */
var addWxUser = function (openid, nick) {
    var defer = Q.defer();
    var Wx = M("index.wx");

    Wx.find({
        where: {
            openid: openid
        }
    }).then(function (user) {
        if (user) {
            defer.resolve();
            return;
        }

        return Wx.create({
            openid: openid,
            nick: nick
        }).then(function () {
            defer.resolve();
        });
    }).catch(function (err) {
        defer.reject(err);
    });

    return defer.promise;
};
/**
 * 保存用户手机号
 * @param openid
 * @param phone
 * @returns {*|promise.promise|jQuery.promise|d.promise|promise}
 */
var saveUserPhone = function (openid, phone) {
    var defer = Q.defer();
    var Wx = M("index.wx");

    Wx.update({
        phone: phone
    }, {
        where: {
            openid: openid
        }
    }).then(function () {
        defer.resolve();
    }).catch(function (err) {
        defer.reject(err);
    });


    return defer.promise;
};


module.exports = router;